package com.example.common.view

import android.animation.ValueAnimator
import android.content.Context
import android.graphics.Canvas
import android.graphics.Color
import android.graphics.Paint
import android.graphics.Point
import android.graphics.SweepGradient
import android.graphics.Typeface
import android.util.AttributeSet
import android.view.View
import android.view.animation.LinearInterpolator
import androidx.core.content.ContextCompat
import com.example.common.R
import kotlin.math.min

/**
 * 自定义圆形倒计时UI组件
 */
class CircleCountDownView@JvmOverloads constructor(context: Context,attrs:AttributeSet?=null,defaultStyle:Int=0):View(context,attrs,defaultStyle) {
    private var progressColor=Color.BLUE
    private var progressBackgroundColor=Color.LTGRAY
    private var progressWidth=20f
    private var textColor=Color.BLACK
    private var textSize=40F
    private var countDownTime=5
    private var textY=0f
    private var centerX=0f
    private var centerY=0f
    private var radius=0f
    private var sweepAngle=0f
    private var currentAngle=0f
    private var remainingTime=5
    private var animator:ValueAnimator?=null
    private var countDownListener:CountDownListener?=null
    //背景画笔样式
    private val backgroundPaint=Paint(Paint.ANTI_ALIAS_FLAG).apply {
        style=Paint.Style.STROKE
        color=progressBackgroundColor
        strokeWidth=progressWidth
        strokeCap=Paint.Cap.ROUND
    }
    //进度条画笔
    private val progressPaint=Paint(Paint.ANTI_ALIAS_FLAG).apply {
        style=Paint.Style.STROKE
        color=progressBackgroundColor
        strokeWidth=progressWidth
        strokeCap=Paint.Cap.ROUND
    }
    //进度条底色画笔
    private val gradientPaint=Paint(Paint.ANTI_ALIAS_FLAG).apply {
        style=Paint.Style.STROKE
        strokeWidth=progressWidth
        strokeCap=Paint.Cap.ROUND
        shader=SweepGradient(centerX,centerY, intArrayOf(Color.RED,Color.YELLOW,Color.GREEN),null)
    }
    //文本画笔
    private val textPaint=Paint(Paint.ANTI_ALIAS_FLAG).apply {
        color=textColor
        textSize=textSize
        textAlign=Paint.Align.CENTER
        typeface=Typeface.DEFAULT_BOLD
    }

    init {
        attrs?.run {
            val typeArray=context.obtainStyledAttributes(this, R.styleable.CircleCountDownView)
             progressColor=typeArray.getColor(R.styleable.CircleCountDownView_progressColor,ContextCompat.getColor(context, com.example.res.R.color.blueviolet))
             progressBackgroundColor=typeArray.getColor(R.styleable.CircleCountDownView_progressBackgroundColor,ContextCompat.getColor(context, com.example.res.R.color.blueviolet))
             progressWidth=typeArray.getDimension(R.styleable.CircleCountDownView_progressWidth,20f)
             textColor=typeArray.getColor(R.styleable.CircleCountDownView_textColor,ContextCompat.getColor(context, com.example.res.R.color.black))
             textSize=typeArray.getDimension(R.styleable.CircleCountDownView_textSize,40f)
            countDownTime=typeArray.getInt(R.styleable.CircleCountDownView_countDownTime,5)
            //释放资源,避免内存泄漏
             typeArray.recycle()
        }
        //重置画笔
        backgroundPaint.strokeWidth=progressWidth
        progressPaint.strokeWidth=progressWidth
        gradientPaint.strokeWidth=progressWidth
        textPaint.color=textColor
        textPaint.textSize=textSize
        //剩余时间
        remainingTime=countDownTime
    }
    fun setCountDownListener(l:CountDownListener){
        countDownListener=l
    }
    override fun onSizeChanged(w: Int, h: Int, oldw: Int, oldh: Int) {
        super.onSizeChanged(w, h, oldw, oldh)
        centerX=w/2f
        centerY=h/2f
        radius=(min(w,h) -progressWidth)/2f
    }

    /**
     * 注意事项:
     * 1.不要在onDraw方法中创建临时变量成对象,避免内存抖动
     * 2.不要做复杂计算
     */
    override fun onDraw(canvas: Canvas) {
        super.onDraw(canvas)
        //绘制背景圆
        canvas.drawCircle(centerX,centerY,radius,backgroundPaint)
        //检测进度条
        sweepAngle=360*(currentAngle/100f)
        canvas.drawArc(centerX-radius,centerX-radius,centerX+radius,centerY+radius,-90f,sweepAngle,false,gradientPaint)
        //绘制文本
        textY=centerY-(textPaint.descent()+textPaint.ascent())/2f
        canvas.drawText("${remainingTime}s跳过",centerX,textY,textPaint)
    }
    /**
     * 开启倒计时
     */
    fun startCountDown(){
        animator=ValueAnimator.ofFloat(0f,100f).apply {
            duration=(countDownTime*1000).toLong()
            interpolator=LinearInterpolator()//匀速执行动画
            //添加监听事件
            addUpdateListener {
                currentAngle=it.animatedValue as Float
                remainingTime=(countDownTime-(currentAngle/100f)*countDownTime).toInt()
                //重新绘制UI
                invalidate()
                //倒计时结束
                if (remainingTime==0){
                    countDownListener?.onCountDownFinish()
                }
            }
        }
        //执行动画
        animator?.start()
    }
    /**
     * 关闭倒计时
     */
    fun stopCountDown(){
        animator?.cancel()
        animator=null
    }

    /**
     * 当组件从窗口解绑回调
     */
    override fun onDetachedFromWindow() {
        super.onDetachedFromWindow()
        stopCountDown()
    }
    /**
     * 定义接口
     */
    interface  CountDownListener{
        fun onCountDownFinish()
    }
}